home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / programr / fileutil.zip / DU.C < prev    next >
C/C++ Source or Header  |  1990-09-03  |  16KB  |  669 lines

  1. /* du -- summarize disk usage
  2.    Copyright (C) 1988, 1989, 1990 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Differences from the Unix du:
  19.    * Doesn't simply ignore the names of regular files given as arguments
  20.      when -a is given.
  21.    * Additional options:
  22.    -l        Count the size of all files, even if they have appeared
  23.         already in another hard link.
  24.    -x        Do not cross file-system boundaries during the recursion.
  25.    -c        Write a grand total of all of the arguments after all
  26.         arguments have been processed.  This can be used to find
  27.         out the disk usage of a directory, with some files excluded.
  28.    -k        Print sizes in kilobytes instead of 512 byte blocks
  29.         (the default required by POSIX).
  30.    -b        Print sizes in bytes (added by POSIX).
  31.  
  32.    By tege@sics.se, Torbjorn Granlund,
  33.    and djm@ai.mit.edu, David MacKenzie.  */
  34.  
  35. #include <stdio.h>
  36. #include <errno.h>
  37. #include <getopt.h>
  38. #include <sys/types.h>
  39. #include "system.h"
  40.  
  41. #ifdef STDC_HEADERS
  42. #include <stdlib.h>
  43. #else
  44. char *malloc ();
  45. char *realloc ();
  46.  
  47. extern int errno;
  48. #endif
  49.  
  50. /* Initial number of entries in each hash table entry's table of inodes.  */
  51. #define INITIAL_HASH_MODULE 100
  52.  
  53. /* Initial number of entries in the inode hash table.  */
  54. #define INITIAL_ENTRY_TAB_SIZE 70
  55.  
  56. /* Initial size to allocate for `path'.  */
  57. #define INITIAL_PATH_SIZE 100
  58.  
  59. /* Hash structure for inode and device numbers.  The separate entry
  60.    structure makes it easier to rehash "in place".  */
  61.  
  62. struct entry
  63. {
  64.   ino_t ino;
  65.   dev_t dev;
  66.   struct entry *coll_link;
  67. };
  68.  
  69. /* Structure for a hash table for inode numbers. */
  70.  
  71. struct htab
  72. {
  73.   unsigned modulus;        /* Size of the `hash' pointer vector.  */
  74.   struct entry *entry_tab;    /* Pointer to dynamically growing vector.  */
  75.   unsigned entry_tab_size;    /* Size of current `entry_tab' allocation.  */
  76.   unsigned first_free_entry;    /* Index in `entry_tab'.  */
  77.   struct entry *hash[1];    /* Vector of pointers in `entry_tab'.  */
  78. };
  79.  
  80.  
  81. /* Structure for dynamically resizable strings. */
  82.  
  83. typedef struct
  84. {
  85.   unsigned alloc;        /* Size of allocation for the text.  */
  86.   unsigned length;        /* Length of the text currently.  */
  87.   char *text;            /* Pointer to the text.  */
  88. } *string, stringstruct;
  89.  
  90. char *savedir ();
  91. char *xmalloc ();
  92. char *xrealloc ();
  93. int hash_insert ();
  94. int hash_insert2 ();
  95. long count_entry ();
  96. void error ();
  97. void hash_init ();
  98. void hash_reset ();
  99. void str_concatc ();
  100. void str_copyc ();
  101. void str_init ();
  102. void str_trunc ();
  103.  
  104. /* Name under which this program was invoked.  */
  105. char *program_name;
  106.  
  107. /* If nonzero, display only a total for each argument. */
  108. int opt_summarize_only = 0;
  109.  
  110. /* If nonzero, display counts for all files, not just directories. */
  111. int opt_all = 0;
  112.  
  113. /* If nonzero, count each hard link of files with multiple links. */
  114. int opt_count_all = 0;
  115.  
  116. /* If nonzero, do not cross file-system boundaries. */
  117. int opt_one_file_system = 0;
  118.  
  119. /* If nonzero, print a grand total at the end. */
  120. int opt_combined_arguments = 0;
  121.  
  122. enum output_size
  123. {
  124.   size_blocks,            /* Default. */
  125.   size_kilobytes,        /* -k. */
  126.   size_bytes            /* -b. */
  127. };
  128.  
  129. /* The units to count in. */
  130. enum output_size output_size = size_blocks;
  131.  
  132. /* Accumulated path for file or directory being processed.  */
  133. string path;
  134.  
  135. /* Pointer to hash structure, used by the hash routines.  */
  136. struct htab *htab;
  137.  
  138. /* Globally used stat buffer.  */
  139. struct stat stat_buf;
  140.  
  141. struct option long_options[] =
  142. {
  143.   {"all", 0, &opt_all, 1},
  144.   {"bytes", 0, NULL, 'b'},
  145.   {"count-links", 0, &opt_count_all, 1},
  146.   {"kilobytes", 0, NULL, 'k'},
  147.   {"one-file-system", 0, &opt_one_file_system, 1},
  148.   {"summarize", 0, &opt_summarize_only, 1},
  149.   {"total", 0, &opt_combined_arguments, 1},
  150.   {NULL, 0, NULL, 0}
  151. };
  152.  
  153. void
  154. usage (reason)
  155.      char *reason;
  156. {
  157.   if (reason != NULL)
  158.     fprintf (stderr, "%s: %s\n", program_name, reason);
  159.  
  160.   fprintf (stderr, "\
  161. Usage: %s [-abcklsx] [+all] [+total] [+count-links] [+summarize]\n\
  162.        [+bytes] [+kilobytes] [+one-file-system] [path...]\n",
  163.        program_name);
  164.  
  165.   exit (2);
  166. }
  167.  
  168. void
  169. main (argc, argv)
  170.      int argc;
  171.      char *argv[];
  172. {
  173.   int c;
  174.   int ind;
  175.  
  176.   program_name = argv[0];
  177.  
  178.   while ((c = getopt_long (argc, argv, "abcklsx", long_options, &ind)) != EOF)
  179.     {
  180.       switch (c)
  181.     {
  182.     case 0:            /* Long option. */
  183.       break;
  184.  
  185.     case 'a':
  186.       opt_all = 1;
  187.       break;
  188.  
  189.     case 'b':
  190.       output_size = size_bytes;
  191.       break;
  192.  
  193.     case 'c':
  194.       opt_combined_arguments = 1;
  195.       break;
  196.  
  197.     case 'x':
  198.       opt_one_file_system = 1;
  199.       break;
  200.  
  201.     case 'k':
  202.       output_size = size_kilobytes;
  203.       break;
  204.  
  205.     case 'l':
  206.       opt_count_all = 1;
  207.       break;
  208.  
  209.     case 's':
  210.       opt_summarize_only = 1;
  211.       break;
  212.  
  213.     default:
  214.       usage ((char *) 0);
  215.     }
  216.     }
  217.  
  218.   if (opt_all && opt_summarize_only)
  219.     usage ("cannot both summarize and show all entries");
  220.  
  221.   /* Initialize the hash structure for inode numbers.  */
  222.  
  223.   hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
  224.  
  225.   str_init (&path, INITIAL_PATH_SIZE);
  226.  
  227.   if (optind == argc)
  228.     {
  229.       str_copyc (path, ".");
  230.  
  231.       /* Initialize the hash structure for inode numbers.  */
  232.  
  233.       hash_reset ();
  234.  
  235.       /* Get the size of the current directory only.  */
  236.  
  237.       count_entry (".", 1, 0);
  238.     }
  239.   else
  240.     {
  241.       char wd[PATH_MAX + 2];
  242.       char *arg;
  243.       ino_t initial_ino;    /* Initial directory's inode. */
  244.       dev_t initial_dev;    /* Initial directory's device. */
  245.       long tot_size = 0;    /* Grand total size of all args. */
  246.  
  247.       if (getwd (wd) == NULL)
  248.     error (1, errno, "cannot get current directory");
  249.  
  250.       /* Remember the inode and device number of the current directory.  */
  251.  
  252.       if (stat (".", &stat_buf))
  253.     error (1, errno, "current directory");
  254.       initial_ino = stat_buf.st_ino;
  255.       initial_dev = stat_buf.st_dev;
  256.  
  257.       do
  258.     {
  259.       int s;
  260.       arg = argv[optind];
  261.  
  262.       /* Delete final slash in the argument, unless the slash is alone.  */
  263.  
  264.       s = strlen (arg) - 1;
  265.       if (s != 0)
  266.         {
  267.           if (arg[s] == '/')
  268.         arg[s] = 0;
  269.  
  270.           str_copyc (path, arg);
  271.         }
  272.       else if (arg[0] == '/')
  273.         str_trunc (path, 0);/* Null path for root directory.  */
  274.       else
  275.         str_copyc (path, arg);
  276.  
  277.       if (!opt_combined_arguments)
  278.         hash_reset ();
  279.  
  280.       tot_size += count_entry (arg, 1, 0);
  281.  
  282.       /* chdir if `count_entry' has changed the working directory.  */
  283.  
  284.       if (stat (".", &stat_buf))
  285.         error (1, errno, ".");
  286.       if ((stat_buf.st_ino != initial_ino
  287.            || stat_buf.st_dev != initial_dev)
  288.           && chdir (wd) < 0)
  289.         error (1, errno, "cannot change to directory %s", wd);
  290.  
  291.       optind++;
  292.     }
  293.       while (optind < argc);
  294.  
  295.       if (opt_combined_arguments)
  296.     {
  297.       printf ("%ld\ttotal\n", output_size == size_bytes ? tot_size
  298.           : convert_blocks (tot_size, output_size == size_kilobytes));
  299.       fflush (stdout);
  300.     }
  301.     }
  302.   exit (0);
  303. }
  304.  
  305. /* Print (if appropriate) and return the size
  306.    (in units determined by `output_size') of file or directory ENT.
  307.    TOP is one for external calls, zero for recursive calls.
  308.    LAST_DEV is the device that the parent directory of ENT is on.  */
  309.  
  310. long
  311. count_entry (ent, top, last_dev)
  312.      char *ent;
  313.      int top;
  314.      dev_t last_dev;
  315. {
  316.   long size;
  317.  
  318.   if (lstat (ent, &stat_buf) < 0)
  319.     {
  320.       error (0, errno, "%s", path->text);
  321.       return 0;
  322.     }
  323.  
  324.   if (!opt_count_all
  325.       && stat_buf.st_nlink > 1
  326.       && hash_insert (stat_buf.st_ino, stat_buf.st_dev))
  327.     return 0;            /* Have counted this already.  */
  328.  
  329.   if (output_size == size_bytes)
  330.     size = stat_buf.st_size;
  331.   else
  332.     {
  333.       size = ST_NBLOCKS (stat_buf);
  334. #ifdef HPUX_NFS_BUG
  335.       if (size >= 2 * (stat_buf.st_size + DEV_BSIZE - 1) / DEV_BSIZE)
  336.     size = (size + 1) / 2;
  337. #endif
  338.     }
  339.  
  340.   if ((stat_buf.st_mode & S_IFMT) == S_IFDIR)
  341.     {
  342.       unsigned pathlen;
  343.       dev_t dir_dev;
  344.       char *name_space;
  345.       char *namep;
  346.  
  347.       dir_dev = stat_buf.st_dev;
  348.  
  349.       if (opt_one_file_system && !top && last_dev != dir_dev)
  350.     return 0;        /* Don't enter a new file system.  */
  351.  
  352.       if (chdir (ent) < 0)
  353.     {
  354.       error (0, errno, "cannot change to directory %s", path->text);
  355.       return 0;
  356.     }
  357.  
  358.       errno = 0;
  359.       name_space = savedir (".", stat_buf.st_size);
  360.       if (name_space == NULL)
  361.     {
  362.       if (errno)
  363.         {
  364.           error (0, errno, "%s", path->text);
  365.           chdir ("..");    /* Try to return to previous directory.  */
  366.           return 0;
  367.         }
  368.       else
  369.         error (1, 0, "virtual memory exhausted");
  370.     }
  371.  
  372.       /* Remember the current path.  */
  373.  
  374.       str_concatc (path, "/");
  375.       pathlen = path->length;
  376.  
  377.       namep = name_space;
  378.       while (*namep != 0)
  379.     {
  380.       str_concatc (path, namep);
  381.  
  382.       size += count_entry (namep, 0, dir_dev);
  383.  
  384.       str_trunc (path, pathlen);
  385.       namep += strlen (namep) + 1;
  386.     }
  387.       free (name_space);
  388.       chdir ("..");
  389.  
  390.       if (!opt_summarize_only || top)
  391.     {
  392.       printf ("%ld\t%s\n", output_size == size_bytes ? size
  393.           : convert_blocks (size, output_size == size_kilobytes),
  394.           path->text);
  395.       fflush (stdout);
  396.     }
  397.     }
  398.   else if (opt_all || top)
  399.     {
  400.       printf ("%ld\t%s\n", output_size == size_bytes ? size
  401.           : convert_blocks (size, output_size == size_kilobytes),
  402.           path->text);
  403.       fflush (stdout);
  404.     }
  405.  
  406.   return size;
  407. }
  408.  
  409. /* Allocate space for the hash structures, and set the global
  410.    variable `htab' to point to it.  The initial hash module is specified in
  411.    MODULUS, and the number of entries are specified in ENTRY_TAB_SIZE.  (The
  412.    hash structure will be rebuilt when ENTRY_TAB_SIZE entries have been
  413.    inserted, and MODULUS and ENTRY_TAB_SIZE in the global `htab' will be
  414.    doubled.)  */
  415.  
  416. void
  417. hash_init (modulus, entry_tab_size)
  418.      unsigned modulus;
  419.      unsigned entry_tab_size;
  420. {
  421.   struct htab *htab_r;
  422.  
  423.   htab_r = (struct htab *)
  424.     xmalloc (sizeof (struct htab) + sizeof (struct entry *) * modulus);
  425.  
  426.   htab_r->entry_tab = (struct entry *)
  427.     xmalloc (sizeof (struct entry) * entry_tab_size);
  428.  
  429.   htab_r->modulus = modulus;
  430.   htab_r->entry_tab_size = entry_tab_size;
  431.   htab = htab_r;
  432.  
  433.   hash_reset ();
  434. }
  435.  
  436. /* Reset the hash structure in the global variable `htab' to
  437.    contain no entries.  */
  438.  
  439. void
  440. hash_reset ()
  441. {
  442.   int i;
  443.   struct entry **p;
  444.  
  445.   htab->first_free_entry = 0;
  446.  
  447.   p = htab->hash;
  448.   for (i = htab->modulus; i > 0; i--)
  449.     *p++ = NULL;
  450. }
  451.  
  452. /* Insert an item (inode INO and device DEV) in the hash
  453.    structure in the global variable `htab', if an entry with the same data
  454.    was not found already.  Return zero if the item was inserted and non-zero
  455.    if it wasn't.  */
  456.  
  457. int
  458. hash_insert (ino, dev)
  459.      ino_t ino;
  460.      dev_t dev;
  461. {
  462.   struct htab *htab_r = htab;    /* Initially a copy of the global `htab'.  */
  463.  
  464.   if (htab_r->first_free_entry >= htab_r->entry_tab_size)
  465.     {
  466.       int i;
  467.       struct entry *ep;
  468.       unsigned modulus;
  469.       unsigned entry_tab_size;
  470.  
  471.       /* Increase the number of hash entries, and re-hash the data.
  472.      The method of shrimping and increasing is made to compactify
  473.      the heap.  If twice as much data would be allocated
  474.      straightforwardly, we would never re-use a byte of memory.  */
  475.  
  476.       /* Let `htab' shrimp.  Keep only the header, not the pointer vector.  */
  477.  
  478.       htab_r = (struct htab *)
  479.     xrealloc ((char *) htab_r, sizeof (struct htab));
  480.  
  481.       modulus = 2 * htab_r->modulus;
  482.       entry_tab_size = 2 * htab_r->entry_tab_size;
  483.  
  484.       /* Increase the number of possible entries.  */
  485.  
  486.       htab_r->entry_tab = (struct entry *)
  487.     xrealloc ((char *) htab_r->entry_tab,
  488.          sizeof (struct entry) * entry_tab_size);
  489.  
  490.       /* Increase the size of htab again.  */
  491.  
  492.       htab_r = (struct htab *)
  493.     xrealloc ((char *) htab_r,
  494.          sizeof (struct htab) + sizeof (struct entry *) * modulus);
  495.  
  496.       htab_r->modulus = modulus;
  497.       htab_r->entry_tab_size = entry_tab_size;
  498.       htab = htab_r;
  499.  
  500.       i = htab_r->first_free_entry;
  501.  
  502.       /* Make the increased hash table empty.  The entries are still
  503.      available in htab->entry_tab.  */
  504.  
  505.       hash_reset ();
  506.  
  507.       /* Go through the entries and install them in the pointer vector
  508.      htab->hash.  The items are actually inserted in htab->entry_tab at
  509.      the position where they already are.  The htab->coll_link need
  510.      however be updated.  Could be made a little more efficient.  */
  511.  
  512.       for (ep = htab_r->entry_tab; i > 0; i--)
  513.     {
  514.       hash_insert2 (htab_r, ep->ino, ep->dev);
  515.       ep++;
  516.     }
  517.     }
  518.  
  519.   return hash_insert2 (htab_r, ino, dev);
  520. }
  521.  
  522. /* Insert INO and DEV in the hash structure HTAB, if not
  523.    already present.  Return zero if inserted and non-zero if it
  524.    already existed.  */
  525.  
  526. int
  527. hash_insert2 (htab, ino, dev)
  528.      struct htab *htab;
  529.      ino_t ino;
  530.      dev_t dev;
  531. {
  532.   struct entry **hp, *ep2, *ep;
  533.   hp = &htab->hash[ino % htab->modulus];
  534.   ep2 = *hp;
  535.  
  536.   /* Collision?  */
  537.  
  538.   if (ep2 != NULL)
  539.     {
  540.       ep = ep2;
  541.  
  542.       /* Search for an entry with the same data.  */
  543.  
  544.       do
  545.     {
  546.       if (ep->ino == ino && ep->dev == dev)
  547.         return 1;        /* Found an entry with the same data.  */
  548.       ep = ep->coll_link;
  549.     }
  550.       while (ep != NULL);
  551.  
  552.       /* Did not find it.  */
  553.  
  554.     }
  555.  
  556.   ep = *hp = &htab->entry_tab[htab->first_free_entry++];
  557.   ep->ino = ino;
  558.   ep->dev = dev;
  559.   ep->coll_link = ep2;        /* `ep2' is NULL if no collision.  */
  560.  
  561.   return 0;
  562. }
  563.  
  564. /* Initialize the struct string S1 for holding SIZE characters.  */
  565.  
  566. void
  567. str_init (s1, size)
  568.      string *s1;
  569.      unsigned size;
  570. {
  571.   string s;
  572.  
  573.   s = (string) xmalloc (sizeof (stringstruct));
  574.   s->text = xmalloc (size + 1);
  575.  
  576.   s->alloc = size;
  577.   *s1 = s;
  578. }
  579.  
  580. static void
  581. ensure_space (s, size)
  582.      string s;
  583.      unsigned size;
  584. {
  585.   if (s->alloc < size)
  586.     {
  587.       s->text = xrealloc (s->text, size + 1);
  588.       s->alloc = size;
  589.     }
  590. }
  591.  
  592. /* Assign the null-terminated C-string CSTR to S1.  */
  593.  
  594. void
  595. str_copyc (s1, cstr)
  596.      string s1;
  597.      char *cstr;
  598. {
  599.   unsigned l = strlen (cstr);
  600.   ensure_space (s1, l);
  601.   strcpy (s1->text, cstr);
  602.   s1->length = l;
  603. }
  604.  
  605. void
  606. str_concatc (s1, cstr)
  607.      string s1;
  608.      char *cstr;
  609. {
  610.   unsigned l1 = s1->length;
  611.   unsigned l2 = strlen (cstr);
  612.   unsigned l = l1 + l2;
  613.  
  614.   ensure_space (s1, l);
  615.   strcpy (s1->text + l1, cstr);
  616.   s1->length = l;
  617. }
  618.  
  619. /* Truncate the string S1 to have length LENGTH.  */
  620.  
  621. void
  622. str_trunc (s1, length)
  623.      string s1;
  624.      unsigned length;
  625. {
  626.   if (s1->length > length)
  627.     {
  628.       s1->text[length] = 0;
  629.       s1->length = length;
  630.     }
  631. }
  632.  
  633. /* Allocate N bytes of memory dynamically, with error checking.  */
  634.  
  635. char *
  636. xmalloc (n)
  637.      unsigned n;
  638. {
  639.   char *p;
  640.  
  641.   p = malloc (n);
  642.   if (p == 0)
  643.     error (1, 0, "virtual memory exhausted");
  644.   return p;
  645. }
  646.  
  647. /* Change the size of an allocated block of memory P to N bytes,
  648.    with error checking.
  649.    If P is NULL, run xmalloc.
  650.    If N is 0, run free and return NULL.  */
  651.  
  652. char *
  653. xrealloc (p, n)
  654.      char *p;
  655.      unsigned n;
  656. {
  657.   if (p == 0)
  658.     return xmalloc (n);
  659.   if (n == 0)
  660.     {
  661.       free (p);
  662.       return 0;
  663.     }
  664.   p = realloc (p, n);
  665.   if (p == 0)
  666.     error (1, 0, "virtual memory exhausted");
  667.   return p;
  668. }
  669.